<?php
namespace SC\Venus;

use Illuminate\Support\ServiceProvider;
use Illuminate\Support\Str;
use Illuminate\Foundation\AliasLoader;
use SC\Venus\Facades\Venus;


class VenusServiceProvider extends ServiceProvider
{
    public function register()
    {
        AliasLoader::getInstance()->alias('Venus', '\SC\Venus\Facades\Venus');
        if ($this->app->runningInConsole()) {
            if ($files = scandir(realpath(__DIR__ . '/Console'))) {
                $commands = [];
                foreach($files as $file) {
                    if (Str::endsWith($file, 'Command.php')) {
                        $commands[] = 'SC\\Venus\\Console\\' . str_replace('.php', '', $file);
                    }
                }
                $this->commands($commands);
            }
        }

        $this->registerMiddleware();
        $this->registerRoutes();
    }

    public function boot()
    {
        $this->loadViewsFrom(__DIR__.'/../resources/views', 'venus');

        $this->publishes([
            __DIR__.'/../publishes/' => public_path('vendor/venus'),
        ]);
    }

    public function registerMiddleware()
    {
        app('router')->aliasMiddleware('venus.auth', Middleware\Auth::class);
        app('router')->aliasMiddleware('venus.guest', Middleware\RedirectIfAuthenticated::class);

        app('router')->middlewareGroup('venus', [
            'venus.auth',
        ]);
    }

    public function registerRoutes()
    {
        app('router')->group([
            'namespace' => 'SC\Venus\Controllers',
            'middleware' => 'web',
            'as' => 'venus.',
            'prefix' => 'venus',
        ], function ($router) {
            $router->get('/login', 'AuthController@showLoginForm')->name('login');
            $router->post('/login', 'AuthController@login')->name('postLogin');
            $router->post('/logout', 'AuthController@logout')->name('logout');
        });

        app('router')->group([
            'as' => 'venus.',
            'prefix' => 'venus',
            'middleware' => ['web', 'venus'],
        ], function ($router) {
            $router->view('/', 'venus::home')->name('home');
            foreach(Venus::discoveryControllers() as $controller) {
                $controller::registerRoute($router);
            }
        });
    }
}